using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using XFFSM;
using XFABManager;
using XFGameFramework;
using UnityEngine.SceneManagement;
using Unity.VisualScripting;
public class Game_Start : FSMState
{
    private StartPanel startPanel;
    private LoadingPanel loadingPanel;
    private Module module;
    private static bool hasEnteredBefore = false;

    public override void OnEnter()
    {
        base.OnEnter();
        Debug.Log("Game_Start OnEnter");

        module = userData as Module;
        if (module == null) throw new System.Exception("userData is not Module");
        if (hasEnteredBefore)
        {
            controller.StartCoroutine(Loading("Start", "StartPanel"));
        }
        else
        {
            module.LoadPanel<StartPanel>();
            hasEnteredBefore = true;
        }
        GameController gameController = module.LoadController<GameController>();
        //使用存档中保存的设置
        gameController.usingsetting();
        Debug.Log("currentArchiveIndex:" + gameController.currentArchiveIndex);
    }

    public override void OnExit()
    {
        base.OnExit();
        Debug.Log("Game_Start OnExit");

        if (startPanel != null)
        {
            startPanel.Close();
            startPanel = null;
        }

    }
    private IEnumerator Loading(string sceneName, string panelName)
    {
        //加载场景
        bool finish = false;

        module.LoadController<SceneController>().LoadScene(sceneName, () =>
        {
            finish = true;
        }, (p) =>
        {
            if (loadingPanel == null) loadingPanel = module.LoadPanel<LoadingPanel>(UIType.DontDestroyUI);//加载loadingPanel,因为跨越两个场景，是不能销毁的UI
            loadingPanel.UpdateProgress(p);
        });
        while (!finish || loadingPanel != null && !loadingPanel.isDone())//?
        {
            yield return null;
        }

        Scene scene = SceneManager.GetSceneByName(sceneName);

        module.LoadPanel(panelName);

        //关闭加载中的场景
        if (loadingPanel != null)
        {
            loadingPanel.Close();
            loadingPanel = null;
        }

    }
}
